<template>
  <div class="admin-page-content">
    <div class="has-top-from-bottom">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="服务名称">
          <el-input placeholder="支持模糊搜索" v-model="query.name" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="search">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="page-btn-box">
      <el-button type="primary" size="small" @click="disableAsync = true">更新服务基础</el-button>
      <el-button type="primary" size="small"
        @click="$router.push({path: '/admin/service-manage/base-service'})">新增基础服务</el-button>
      <el-button type="primary" size="small"
        @click="$router.push({path: '/admin/service-manage/advanced-service'})">新增进阶服务</el-button>
      <!-- <el-button type="primary" size="small" @click="$router.push('/admin/service-manage/dev')">专业运维功能</el-button> -->
      <el-button type="primary" size="small" @click="todevUrl">专业运维功能</el-button>
    </div>
    <el-table v-loading="loading" :data="data" style="width: 100%;" border size="small" ref="serviceTable">
      <el-table-column label="id" prop="id"></el-table-column>
      <el-table-column label="服务名称" prop="name"></el-table-column>
      <el-table-column label="服务类型" prop="type">
        <template slot-scope="scope">
          <el-tag effect="dark" size="mini" v-if="scope.row.type === 0">基础服务</el-tag>
          <el-tag type="success" effect="dark" size="mini" v-if="scope.row.type === 1">进阶服务</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="副本数" prop="replicas"></el-table-column>
      <el-table-column label="服务启停" prop="status">
        <template slot-scope="scope">
          <el-tag effect="plain" size="mini" type="danger" v-if="scope.row.status === 0">未部署</el-tag>
          <el-tag effect="plain" size="mini" type="success" v-if="scope.row.status === 1">已启动</el-tag>
          <el-tag effect="plain" size="mini" type="warning" v-if="scope.row.status === 2">已停用</el-tag>
          <el-tag effect="plain" size="mini" type="info" v-if="scope.row.status === 3">已禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="返回方式" prop="resultType">
        <template slot-scope="scope">
          <span v-if="scope.row.resultType === 0"> JSON </span>
          <span v-if="scope.row.resultType === 1"> XML </span>
          <span v-if="scope.row.resultType === 2"> NAS </span>
          <span v-if="scope.row.resultType === 3"> FTP </span>
        </template>
      </el-table-column>
      <el-table-column label="返回方式" prop="createTime">
        <template slot-scope="scope">{{moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss')}}</template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <i class="icon-table edit-icon" @click="editService(scope.row)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <i class="icon-table delete-icon" @click="deleteService(scope.row)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="启用" placement="top" v-if="scope.row.status !== 1 && scope.row.status !== 9">
            <i class="icon-table icon-qiyong" @click="setServiceStatus(scope.row,1)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="停用" placement="top"
            v-if="scope.row.status !== 0 && scope.row.status !== 2 && scope.row.status !== 9">
            <i class="icon-table icon-tingyong" @click="setServiceStatus(scope.row,2)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="设置副本数" placement="top">
            <i class="icon-table info-icon" @click="setScale(scope.row)"></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination">
      <el-pagination background @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="query.pageNumber"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="100"
      layout="sizes, prev, pager, next"
      :total="total"></el-pagination>
      <span class="span-pagination">共{{Math.ceil(total/query.pageSize)}}页,{{total}}条数据</span>
    </div>
    <el-dialog title="更新基础服务包" :close-on-press-escape="false" width="30%"
      :close-on-click-modal="false" :visible.sync="disableAsync">
      <el-form :model="input" :rules="inputRules" ref="versForm"  label-width="120px" class="demo-ruleForm">
        <el-form-item label="应用类型：" prop="dbType">
          <el-select v-model="input.dbType" @change="selectBDtype">
            <el-option label="oracle" :value="0"></el-option>
            <el-option label="hive" :value="1"></el-option>
            <el-option label="kudu" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最新版本号：" prop="newVersion">
           <el-select v-model="input.newVersion">
            <el-option v-for="item in versionList" :key="item" :label="item" :value="item"></el-option>
           </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" @click.native="cancelSubmit">取消</el-button>
        <el-button type="primary" @click.native="submitFrom('versForm')">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑副本数" :close-on-press-escape="false" width="30%"
      :close-on-click-modal="false" :visible.sync="numbersDialog">
      <el-form :model="numbersInfo" :rules="numbersInfoRules" ref="numberForm" label-position="top"  label-width="120px" class="demo-ruleForm">
        <el-form-item label="副本数" prop="count">
          <el-input-number v-model="numbersInfo.count" controls-position="right"
            style="width:100%"
            :min="count === 0 ? 0 : count-1" :max="count+1">
          </el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" @click.native="cancelNumberSubmit">取消</el-button>
        <el-button type="primary" v-loading="loadingNumber" @click.native="submitNumberFrom('numberForm')">
          {{loadingNumber ? '正在设置中' : '保存' }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { getServiceList, setScale, switchService, deleteServiceInfo,
getPackageVersionList, batchUpdateBasePackage } from '@/api/admin/service';
import moment from 'moment';
import { getK8sInfo } from '@/api/admin/service'
export default {
  data() {
    return {
      query: {
        name: '',
        pageSize:10,
        pageNumber:1
      },
      loading: true,
      total: 0,
      data: [],
      version: [],
      disableAsync: false,
      input: {
        dbType: '',
        newVersion: ''
      },
      inputRules: {
        dbType: [ {required:true, message: '请选择应用类型', trigger: 'change'}],
        newVersion: [ {required:true, message: '请选择版本号', trigger: 'change'} ]
      },
      versionList: [],
      numbersDialog: false,
      numbersInfo: {
        appId: '',
        count: 0
      },
      count: 0,
      numbersInfoRules: {
        count: [{required:true,message:'请输入副本数', trigger:'blur'}]
      },
      loadingNumber: false,
    }
  },
  mounted() {
    this.serviceList()
    this.initPageData()
  },
  methods: {
    moment,
    // 专业运维功能
    todevUrl(){
      const vm = this;
      const loading = this.$loading({
        lock: true,
        text: `正在获取机器集群运维数据,请耐心等待`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      getK8sInfo().then((response) => {
        loading.close()
        if (response.code === '20000') {
          window.open(response.data.url+'login','_blank')
        }else {
          
          vm.$message.error('获取地址失败')
        }
      })
    },
    // 编辑副本数
    submitNumberFrom(rulefrom) {
      const vm = this;
      vm.$refs[rulefrom].validate((valid) =>{
        if (valid) {
          vm.loadingNumber = true
          setScale(vm.numbersInfo).then((responese)=> {
            vm.loadingNumber = false
            if(responese.code === '20000') {
              vm.numbersDialog = false;
              vm.$message.success('设置副本数成功');
              vm.serviceList()
            }
          })
        }
      })
    },
    // 取消编辑副本数
    cancelNumberSubmit() {
      this.numbersInfo = this.$options.data().numbersInfo
      this.count = 0
      this.numbersDialog  = false
    },
    // 编辑
    editService(row) {
      if(row.type === 0) {
        this.$router.push({
          path: '/admin/service-manage/base-service',
          query: {
            id:row.id
          }
        })
      } else {
        this.$router.push({
          path: '/admin/service-manage/advanced-service',
          query: {
            id:row.id
          }
        })
      }
      
    },
    // 更新服务基础包
    async submitFrom(fromRule) {
      const vm = this;
      vm.$refs[fromRule].validate((valid) => {
        if (valid) {
          batchUpdateBasePackage(vm.input).then((responese) => {
            if (responese.code === '20000') {
              vm.$message.success('更新成功');
              vm.serviceList()
              vm.input = vm.$options.data().input;
              vm.versionList = vm.$options.data().versionList;
              vm.disableAsync = vm
            }
          })
        }
      })
    },
    cancelSubmit() {
      this.input = this.$options.data().input;
      this.versionList = this.$options.data().versionList;
      this.disableAsync = false
    },
    selectBDtype(val) {
      const vm = this;
      let key = val === 0 ? 'oraclebase' : ( val === 1 ? 'hivebase' : 'kudubase')
      vm.versionList = vm.version[key]
    },
    async initPageData() {
      const vm = this;
      let responese = await getPackageVersionList()
      if (responese.code === '20000') {
        vm.version = responese.data
      }
    },
    // 删除服务
    deleteService(row) {
      const vm = this;
      vm.$confirm(`此操作将导致服务或者应用不可用，请谨慎操作，是否继续`,`删除服务`,{
        confirmButtonText: `确定删除`,
        cancelButtonText: `取消删除`,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if(action=== 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = `删除中...`;
            deleteServiceInfo({id:row.id}).then((response) => {
              instance.confirmButtonLoading = false;
              if (response.code === '20000') {
                vm.$message.success('删除成功');
                vm.serviceList()
                done();
              }
            })
          }else {
            done()
          }
        }
      }).catch(() => {
        vm.$message.info('已取消')
      })  
    },
    // 启用或者停用
    setServiceStatus(row,status) {
      const vm = this;
      let status_text = status === 1 ? '启用' : '停用';
      vm.$confirm(`${status_text}服务，请谨慎操作，是否继续？`, `${status_text}服务`, {
        confirmButtonText: `确认${status_text}`,
        cancelButtonText: `取消${status_text}`,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = `${status_text}中...`;
            switchService({id:row.id,start:status===1?true:false}).then((response)=>{
              instance.confirmButtonLoading = false;
              if(response.code === '20000') {
                done();
                vm.$message.success(`${status_text}成功`);
                vm.serviceList()
              }
            })
          }else {
            done()
          }
        }
      })
      .then(() => {})
      .catch(() => {
        vm.$message.info('已取消')
      })
    },
    // 设置副本数
    setScale(row) {
      const vm = this;
      vm.numbersInfo = {
        appId: row.id,
        count: row.replicas
      }
      vm.count = row.replicas
      vm.numbersDialog = true
      // return
      // vm.$prompt(`输入要设置(${row.name})服务的副本数`,`设置副本数`, {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   closeOnClickModal: false,
      //   closeOnPressEscape: false,
      //   inputType: 'number',
      //   inputValue:row.replicas,
      //   inputPattern:/(^[1-9]\d$)/,
      //   inputErrorMessage: '请输入正确的副本数'
      // })
      // .then(({ value }) => {
      //   setScale({appId:row.id,count:value}).then((responese)=> {
      //     if(responese.code === '20000') {
      //       vm.$message.success('设置副本数成功');
      //       vm.serviceList()
      //     }
      //   })
      // })
      // .catch(() => {
      //   // vm.$message.info('取消修改')
      // })
    },
    // 查询
    search() {
      this.query.pageNumber = 1;
      this.serviceList()
    },
    handleSizeChange(val) {
      this.query.pageSize=val;
      this.serviceList()
    },
    handleCurrentChange(val) {
      this.query.pageSize = val;
      this.serviceList()
    },
    async serviceList() {
      const vm = this;
      vm.loading = true;
      let response = await getServiceList(vm.query);
      vm.loading = false;
      if (response.code === '20000') {
        vm.data = response.data.list;
        vm.total = response.data.total;
      }
    }
  }
}
</script>